const Attachments = require('../model/Attachment');
const path = require('path');
const fs = require('fs');
const { promisify } = require('util');
const renamePromisify = promisify(fs.rename);
const unlinkPromisify = promisify(fs.unlink);

let attachmentsController = {};

attachmentsController.uploadPicture = async (req, res) => {
  let file = req.file;
  let cover;
  if (file) {
    let { originalname, destination, filename } = file;
    const oldPath = path.join(destination, filename);
    // const oldPath = destination + '/' + filename;
    const suffix = originalname.substring(originalname.lastIndexOf('.'));
    newPath = oldPath + suffix;
    await renamePromisify(oldPath, newPath);
    cover = newPath;
  }
  Attachments.create({
    picture: cover,
  });

  res.json(cover);
};

attachmentsController.getAllPicture = async (req, res) => {
  let data = await Attachments.findAll();
  //   console.log(data);
  res.json(data);
};

attachmentsController.delPicture = async (req, res) => {
  let { picture } = req.body;
  let { dataValues } = await Attachments.findOne({ where: { picture } });
  let id = dataValues.id;
  await Attachments.destroy({ where: { id } });
  await unlinkPromisify(picture)
    .then(() => {
      res.json({ code: 20000, message: '删除成功' });
    })
    .catch(() => {
      res.json({ code: 20001, message: '删除失败' });
    });
};
module.exports = attachmentsController;
